import numpy as np
import sys

X = np.array([[0, 2], [0, 0], [1, 0], [5, 0], [5, 2]])

# n样本点的数目，k聚类的个数, m为每个样本具有的属性值
n = X.shape[0]
m = X.shape[1]
k = 2

#生成k个初始类
#直接将X[i]的样本点作为类的中心
cluster = []
g_list = [[] for i in range(k)]

for i in range(k):
    g_list[i].append(X[i])
    cluster.append(X[i])

#是否是第一次运行，第一次要从k开始，之后从0开始
first = True
while True:
    if first:
        s = k
    else:
        s = 0
    for i in range(s, n):
        # 计算欧氏距离的平方
        # d记录最大的欧氏距离，l记录与当前样本向量 i距离最近的cluster分类的
        d = sys.maxsize
        l = 0
        for j in range(k):
            distance = np.sum(np.square(X[i] - cluster[j]))
            if distance < d:
                d = distance
                l = j
        ## X[i]应该分到 l 类，
        g_list[l].append(X[i])

    # 重新计算中心
    new_cluster = []
    for i in range(k):
        t = np.zeros(m)
        for sample in g_list[i]:
            t = t + sample
        t = t / len(g_list[i])
        new_cluster.append(t)

    #判断俩次族向量是否相同，如果相同停止分类
    stop = True
    for i in range(k):
        for j in range(m):
            if cluster[i][j] != new_cluster[i][j]:
                stop = False
    if stop:
        break
    else:
        g_list = [[] for i in range(k)]
    cluster = new_cluster
    first = False

print(cluster)
print(g_list)

##cluster即可认为是训练的结果，对于测试数据集，与cluster中的中心点依次计算距离，最近的就是所属的类。

